<?php

namespace App\HttpController\Applet\Xiaoyingtao;



use App\Model\WechatsModel;
use App\Utility\Cache;
use Carbon\Carbon;

/**
 * @title 首页
 * @description 首页控制器
 * @method GET
 * @request go
 * @param int id 文章ID true 0
 * @param string code 验证码 false ''
 * @return int code 状态码（0成功1失败）
 * @return string msg 提示信息
 * @return int userid 用户ID
 * @example {title: "首页",description: "首页控制器",method: "GET",request: "https://baby.chumomei.com/go"}
 */
class IndexController extends AuthController {

    public function index(){
        $request= $this->request();
        $chanel = trim($request->getRequestParam('chanel_id')) ?: 0;
        $option = trim($request->getRequestParam('option')) ?: 0;

        $cache = new Cache();
        $cacheName = 'datas-'.$this->applet.'-'.$chanel.'-'.$option;
        $cacheDate = $cache->get($cacheName);
        if(!$cacheDate){
            $appletVideoName = $this->appletVideoModel($this->applet);
            $model = new $appletVideoName;
            $lists = $model->select('videos_xiaoyingtao.id,title,videos_xiaoyingtao.thumb,c.name,c.thumb as avatar')
                ->join('categorys as c','c.id = videos_xiaoyingtao.cateid')
                ->where(function($query) use($chanel,$option){
                    if ($chanel){
                        $query->where('chanel_id',$chanel);
                    }
                    if ($option){
                        $query->where('`option`',2);
                    }
                })
                ->where('status',1)
                ->inRandomOrder()
                ->take(40)
                ->get();
            $cache->set($cacheName,$lists,2);
        }else{
            $lists = $cacheDate;
        }

        return $this->writeJson(0,$lists);
    }


    public function info(){
        $request= $this->request();
        $id = $request->getRequestParam('id');
        $share = $request->getRequestParam('share') ?? null;
        $openid = $request->getRequestParam('openid') ?? '';
        $appletVideoName = $this->appletVideoModel($this->applet);
        $model = new $appletVideoName;
        $info = $model->select('id,title,thumb,link,userid')
            ->find($id);
        if(!$info){
            return $this->writeJson(1,null,'数据信息不存在');
        }
        //匹配腾讯视频的vid
        if(strlen($info['link']) !== 11){
            preg_match_all('/\/([0-9a-zA-Z]+).html/', $info['link'], $matchs);
            $vid = $matchs[1][0] ?: '';
            $info['vid'] = $vid;
        }

        //开启任务-创建统计自增推送队列
        $queueData = [
            'id' => $id,
            'admin_id' => $info['userid'],
            'share' => $share,
            'openid' => $openid,
            'applet' => $this->applet,
            'applet_type' => 'video',
        ];

        $queue = new Cache();
        $queue->onQueue('count-inc');
        $queue->push($queueData);
        return $this->writeJson(0,$info);
    }



    public function randList(){
        $request= $this->request();
        $id = $request->getRequestParam('id');
        if (empty($id)) {
            return $this->writeJson(1, null,'参数错误');
        }
        $appletVideoName = $this->appletVideoModel($this->applet);
        $model = new $appletVideoName;
        $lists = $model->select('id,title,thumb')
            ->where('status',1)
            ->where('id', $id, '<>')
            ->take(20)
            ->inRandomOrder()
            ->get();
        return $this->writeJson(0, $lists);
    }


    public function getBanner(){
        $appletVideoName = $this->appletVideoModel($this->applet);
        $model = new $appletVideoName;
        $lists = $model->select('id,title,thumb')
            ->where('banner', 2)
            ->get();
        return $this->writeJson(0, $lists);
    }

    //收集模板消息的formid
    public function formId(){
        try{
            $request = $this->request();
            $data = $request->getRequestParam();
            if($data['formid'] =='the formId is a mock one'){
                return $this->writeJson(1,null,'测试数据');
            }
            if(!isset($data['openid']) || !$data['openid']){
                return $this->writeJson(1,null,'参数错误');
            }
            $queue = new Cache();
            $queue->onQueue('formid');
            $queue->push([
                'openid' => $data['openid'],
                'expire' => Carbon::now()->addDays(7)->timestamp,
                'formid' => $data['formid'],
                'name'   => $this->applet
            ]);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    public function config(){
        $request = $this->request();
        $name= $request->getRequestParam('name') ?? '';
        if(!$name){
            return $this->writeJson(1,null,'参数不正确');
        }
        $appletVideoName = $this->appletConfigModel($this->applet);
        $model = new $appletVideoName;
        $list = $model->where('name',$name)->first();
        return $this->writeJson(0,$list);
    }
    /**
     * 获取公众号链接文章
     */
    public function wechatLink(){
        $request = $this->request();
        $position = $request->getRequestParam('position') ?? 1;
        $cache = new Cache();
        $cacheName = 'datas-'.$this->applet.'-position-'.$position;
        $cacheDate = $cache->get($cacheName);
        if(!$cacheDate){
            $appletModel = new WechatsModel();
            $list = $appletModel->where('position',$position)->where('name',$this->applet)->get();
            $cache->set($cacheName,$list,2);
        }else{
            $list = $cacheDate;
        }
        return $this->writeJson(0,$list);
    }

    /**
     * 获取预约状态
     */
    public function reserve(){
        $request= $this->request();
        $params = $request->getRequestParam();
        if(!$params['openid']){
            return $this->writeJson(1,null,'参数不正确');
        }
        $userModelName = $this->appletUserModel($this->applet);
        $userModel = new $userModelName;
        $userInfo = $userModel->where('openid',$params['openid'])->first();

        return $this->writeJson(0,['status'=>$userInfo['status']],'ok');
    }

    /**
     * 更新预约状态
     */
    public function reserveUpdate(){
        $request= $this->request();
        $params = $request->getRequestParam();
        if(!$params['openid']){
            return $this->writeJson(1,null,'参数不正确');
        }
        $userModelName = $this->appletUserModel($this->applet);
        $userModel = new $userModelName;
        $userInfo = $userModel->where('openid',$params['openid'])->first();
        if($userInfo){
            if($userInfo['status'] == 1){
                $userInfo['status'] = 2;
                $isUpdate = $userModel->update($userInfo);
                if($isUpdate){
                    return $this->writeJson(0,null,'已取消订阅');
                }
            }else{
                $userInfo['status'] = 1;
                $isUpdate = $userModel->update($userInfo);
                if($isUpdate){
                    return $this->writeJson(0,null,'订阅成功');
                }
            }
            return $this->writeJson(1,null,'error');
        }
        return $this->writeJson(1,null,'error:'.$params['openid']);

    }
}
